package com.ltv.xiangqibook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.ltv.xiangqibook.common.GameIDCreator;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class TreeGenerator {
    
    public synchronized void initTree(File path, String gameId) throws Exception {
        createXML(path);
    }
    
    public static void main(String[] args) {
    	try {
			createXML(new File(args[0]));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    private static void createXML(File path) throws Exception {

        // initiating document factory
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element rootElement = document.createElement("Folder");
        document.appendChild(rootElement);

        rootElement.setAttribute("value", path.getName());

        // First call to explore the path
        listDirectories(rootElement, document, path, path.getAbsolutePath());

        //print
        OutputFormat format = new OutputFormat(document);
        format.setIndenting(true);
        format.setLineWidth(Integer.MAX_VALUE);

        //to generate output to console use this serializer
        //XMLSerializer serializer = new XMLSerializer(System.out, format);

        //to generate a file output use fileoutputstream instead of system.out
        XMLSerializer serializer = new XMLSerializer(
                new FileOutputStream(new File("xiangqibook-tree.xml")), format);

        serializer.serialize(document);
    }
    
    private static void listDirectories(Element rootElement, Document document,
            File dir, String bookLocation) throws Exception {

        File[] child = dir.listFiles();
        Arrays.sort(child);
        for (File f : child) {
            if (f.isDirectory()) { // is it a directory?
            	if (f.getName().indexOf(".svn") == -1) {
                    Element childElement = document.createElement("Folder");
                    
                    String displayValue = "";
                    String fileName = f.getName();
                    int index = f.getName().indexOf('_');
                    int gameIndex = -1;
                    
                    if (index >= 0) {
                        try {
                            gameIndex = Integer.parseInt(fileName.substring(0, index));
                        } catch (Exception e) {
                            gameIndex = -1;
                        }
                    }
                    
                    if (gameIndex != -1) {
                        displayValue = fileName.substring(index + 1, fileName.length());
                    } else {
                        displayValue = fileName.substring(0, fileName.length());
                    }
                    
                    childElement.setAttribute("value", displayValue);
                    childElement.setAttribute("fullpath", f.getAbsolutePath().replace(bookLocation, ""));
    
                    // appending the found dir name to the root element
                    rootElement.appendChild(childElement);
    
                    // Recurssive call to the same method where we find any folder
                    // in parent folder
                    listDirectories(childElement, document, f.getAbsoluteFile(), bookLocation);
            	}

            } else { // what else? it is a file and for a file there is
                // no recursive call obviously ;)
                if (f.getName().endsWith(".pgn")) {
                    Element childElement = document.createElement("File");
                    
                    String displayValue = "";
                    String fileName = f.getName();
                    int index = f.getName().indexOf('_');
                    int gameIndex = -1;
                    
                    if (index >= 0) {
                        try {
                            gameIndex = Integer.parseInt(fileName.substring(0, index));
                        } catch (Exception e) {
                            gameIndex = -1;
                        }
                    }
                    
                    if (gameIndex != -1) {
                        displayValue = fileName.substring(index + 1, fileName.length() - 4);
                    } else {
                        displayValue = fileName.substring(0, fileName.length() - 4);
                    }
                    
                    childElement.setAttribute("value", displayValue);
                    
                    childElement.setAttribute("game_id", GameIDCreator.getGameID(f, bookLocation));
                    
                    // appending the found file name to the root element
                    rootElement.appendChild(childElement);
                } else if (f.getName().endsWith(".html")) {
                    Element childElement = document.createElement("File");
                    
                    String displayValue = "";
                    String fileName = f.getName();
                    int index = f.getName().indexOf('_');
                    int gameIndex = -1;
                    
                    if (index >= 0) {
                        try {
                            gameIndex = Integer.parseInt(fileName.substring(0, index));
                        } catch (Exception e) {
                            gameIndex = -1;
                        }
                    }
                    
                    if (gameIndex != -1) {
                        displayValue = fileName.substring(index + 1, fileName.length() - ".html".length());
                    } else {
                        displayValue = fileName.substring(0, fileName.length() - ".html".length());
                    }
                    
                    childElement.setAttribute("value", displayValue);
                    
                    childElement.setAttribute("game_id", GameIDCreator.getGameID(f, bookLocation));
                    
                    // appending the found file name to the root element
                    rootElement.appendChild(childElement);
                }
            }
        }

    }
    
}
